package com.it.labservice.controller;

import com.it.labservice.service.CollegeService;
import com.it.labservice.repository.*;
import com.it.labservice.entity.Term;
import com.it.labservice.entity.User;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import java.time.LocalDate;

@Controller
public class MainController {
    
    @Autowired
    private CollegeRepository collegeRepository;
    
    @Autowired
    private TermRepository termRepository;
    
    @Autowired
    private LaboratoryRepository laboratoryRepository;
    
    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private SafetyCheckRepository safetyCheckRepository;
    
    @GetMapping("/")
    public String index(Model model, HttpSession session) {
        // 检查用户是否已登录
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null) {
            return "redirect:/login";
        }
        
        // 重新从数据库获取用户信息（确保数据最新）
        currentUser = userRepository.findById(currentUser.getId()).orElse(currentUser);
        
        // 根据用户角色进行跳转
        if (User.UserRole.ADMIN.equals(currentUser.getRole())) {
            // 超级管理员跳转到仪表盘
            return "redirect:/dashboard";
        }
        
        // 实验室管理员显示安全检查系统
        model.addAttribute("currentUser", currentUser);
        
        // 基础数据
        model.addAttribute("colleges", collegeRepository.findAll());
        model.addAttribute("terms", termRepository.findAll());
        model.addAttribute("laboratories", laboratoryRepository.findAll());
        model.addAttribute("users", userRepository.findAll());
        
        // 实验室管理员列表（角色为LAB_MANAGER的用户）
        model.addAttribute("labManagers", userRepository.findAll().stream()
                .filter(user -> com.it.labservice.entity.User.UserRole.LAB_MANAGER.equals(user.getRole()))
                .toList());
        
        // 最近的安全检查记录
        var recentRecords = safetyCheckRepository.findAll().stream()
                .sorted((a, b) -> b.getCheckDate().compareTo(a.getCheckDate()))
                .limit(4)
                .toList();
        model.addAttribute("recentRecords", recentRecords);
        
        // 所有安全检查记录（用于记录查询页面）
        model.addAttribute("safetyRecords", safetyCheckRepository.findAll());
        
        return "index";
    }
    
    @GetMapping("/dashboard")
    public String dashboard(Model model, HttpSession session) {
        // 检查用户是否已登录
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null) {
            return "redirect:/login";
        }
        
        // 只有超级管理员可以访问仪表盘
        if (!User.UserRole.ADMIN.equals(currentUser.getRole())) {
            return "redirect:/";
        }
        
        // 重新从数据库获取用户信息（确保数据最新）
        currentUser = userRepository.findById(currentUser.getId()).orElse(currentUser);
        model.addAttribute("currentUser", currentUser);
        
        // 统计数据
        var statistics = new java.util.HashMap<String, Object>();
        statistics.put("collegeCount", collegeRepository.count());
        statistics.put("labCount", laboratoryRepository.count());
        statistics.put("managerCount", userRepository.countByRole(User.UserRole.LAB_MANAGER));
        statistics.put("todayCheckCount", safetyCheckRepository.findByCheckDate(LocalDate.now()).size());
        model.addAttribute("statistics", statistics);
        
        // 最近的安全检查记录
        var recentRecords = safetyCheckRepository.findAll().stream()
                .sorted((a, b) -> b.getCheckDate().compareTo(a.getCheckDate()))
                .limit(5)
                .toList();
        model.addAttribute("recentRecords", recentRecords);
        
        return "dashboard";
    }
    
    @GetMapping("/college")
    public String college(Model model) {
        model.addAttribute("colleges", collegeRepository.findAll());
        return "index";
    }
    
    @GetMapping("/term")
    public String term(Model model) {
        model.addAttribute("terms", termRepository.findAll());
        return "index";
    }
    
    @GetMapping("/lab")
    public String lab(Model model) {
        model.addAttribute("laboratories", laboratoryRepository.findAll());
        return "index";
    }
    
    @GetMapping("/user")
    public String user(Model model) {
        model.addAttribute("users", userRepository.findAll());
        return "index";
    }
    
    @GetMapping("/lab-manager")
    public String labManager(Model model) {
        model.addAttribute("users", userRepository.findAll());
        model.addAttribute("laboratories", laboratoryRepository.findAll());
        return "index";
    }
    
    @GetMapping("/check")
    public String check(Model model, HttpSession session) {
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null) {
            return "redirect:/login";
        }
        
        // 只有实验室管理员可以访问
        if (User.UserRole.ADMIN.equals(currentUser.getRole())) {
            return "redirect:/dashboard";
        }
        
        model.addAttribute("terms", termRepository.findAll());
        model.addAttribute("laboratories", laboratoryRepository.findAll());
        return "index";
    }
    
    @GetMapping("/records")
    public String records(Model model, HttpSession session) {
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null) {
            return "redirect:/login";
        }
        
        // 只有实验室管理员可以访问
        if (User.UserRole.ADMIN.equals(currentUser.getRole())) {
            return "redirect:/dashboard";
        }
        
        model.addAttribute("terms", termRepository.findAll());
        model.addAttribute("laboratories", laboratoryRepository.findAll());
        model.addAttribute("safetyChecks", safetyCheckRepository.findAll());
        return "index";
    }
    
    @GetMapping("/college-management")
    public String collegeManagement(Model model, HttpSession session) {
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null) {
            System.out.println("DEBUG: 用户未登录，重定向到登录页面");
            return "redirect:/login";
        }
        
        System.out.println("DEBUG: 当前用户: " + currentUser.getUsername() + ", 角色: " + currentUser.getRole());
        
        // 只有超级管理员可以访问
        if (!User.UserRole.ADMIN.equals(currentUser.getRole())) {
            System.out.println("DEBUG: 用户角色不是ADMIN，重定向到首页");
            return "redirect:/";
        }
        
        // 重新从数据库获取用户信息
        currentUser = userRepository.findById(currentUser.getId()).orElse(currentUser);
        model.addAttribute("currentUser", currentUser);
        model.addAttribute("colleges", collegeRepository.findAll());
        
        System.out.println("DEBUG: 成功访问学院管理页面");
        return "college-management";
    }
    
    @GetMapping("/term-management")
    public String termManagement(Model model, HttpSession session) {
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null) {
            return "redirect:/login";
        }
        
        // 只有超级管理员可以访问
        if (!User.UserRole.ADMIN.equals(currentUser.getRole())) {
            return "redirect:/";
        }
        
        currentUser = userRepository.findById(currentUser.getId()).orElse(currentUser);
        model.addAttribute("currentUser", currentUser);
        model.addAttribute("terms", termRepository.findAll());
        
        return "term-management";
    }
    
    @GetMapping("/laboratory-management")
    public String laboratoryManagement(Model model, HttpSession session) {
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null) {
            return "redirect:/login";
        }
        
        // 只有超级管理员可以访问
        if (!User.UserRole.ADMIN.equals(currentUser.getRole())) {
            return "redirect:/";
        }
        
        currentUser = userRepository.findById(currentUser.getId()).orElse(currentUser);
        model.addAttribute("currentUser", currentUser);
        model.addAttribute("laboratories", laboratoryRepository.findAll());
        model.addAttribute("colleges", collegeRepository.findAll());
        
        return "laboratory-management";
    }
    
    @GetMapping("/user-management")
    public String userManagement(Model model, HttpSession session) {
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null) {
            return "redirect:/login";
        }
        
        // 只有超级管理员可以访问
        if (!User.UserRole.ADMIN.equals(currentUser.getRole())) {
            return "redirect:/";
        }
        
        currentUser = userRepository.findById(currentUser.getId()).orElse(currentUser);
        model.addAttribute("currentUser", currentUser);
        model.addAttribute("users", userRepository.findAll());
        model.addAttribute("colleges", collegeRepository.findAll());
        
        return "user-management";
    }
    
    @GetMapping("/assignment-management")
    public String assignmentManagement(Model model, HttpSession session) {
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null) {
            return "redirect:/login";
        }
        
        // 只有超级管理员可以访问
        if (!User.UserRole.ADMIN.equals(currentUser.getRole())) {
            return "redirect:/";
        }
        
        currentUser = userRepository.findById(currentUser.getId()).orElse(currentUser);
        model.addAttribute("currentUser", currentUser);
        model.addAttribute("users", userRepository.findByRole(User.UserRole.LAB_MANAGER));
        model.addAttribute("laboratories", laboratoryRepository.findAll());
        
        return "assignment-management";
    }
    
    @GetMapping("/safety-check")
    public String safetyCheck(Model model, HttpSession session) {
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null) {
            return "redirect:/login";
        }
        
        // 只有实验室管理员可以访问安全检查页面
        if (User.UserRole.ADMIN.equals(currentUser.getRole())) {
            return "redirect:/dashboard";  // 超级管理员重定向到仪表盘
        }
        
        // 重新从数据库获取用户信息（包括关联的实验室）
        currentUser = userRepository.findByIdWithLaboratories(currentUser.getId()).orElse(currentUser);
        model.addAttribute("currentUser", currentUser);
        
        // 只传递激活的学期
        model.addAttribute("terms", termRepository.findByStatus(Term.TermStatus.CURRENT));
        
        // 获取当前用户管理的实验室
        model.addAttribute("userLaboratories", currentUser.getLaboratories());
        
        return "safety-check";
    }
    
    @GetMapping("/safety-records")
    public String safetyRecords(Model model, HttpSession session) {
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null) {
            return "redirect:/login";
        }
        
        // 只有实验室管理员可以访问安全检查记录页面
        if (User.UserRole.ADMIN.equals(currentUser.getRole())) {
            return "redirect:/dashboard";  // 超级管理员重定向到仪表盘
        }
        
        // 重新从数据库获取用户信息（包括关联的实验室）
        currentUser = userRepository.findByIdWithLaboratories(currentUser.getId()).orElse(currentUser);
        model.addAttribute("currentUser", currentUser);
        
        // 基础数据
        model.addAttribute("terms", termRepository.findAll());
        model.addAttribute("userLaboratories", currentUser.getLaboratories());
        model.addAttribute("safetyRecords", safetyCheckRepository.findAll());
        
        return "safety-records";
    }
} 